<?php

namespace App\Http\Controllers\Logic;

use App\Exceptions\BusinessException;
use App\Http\Controllers\Constant\Constant;
use App\Http\Controllers\Controller;
use App\Http\Controllers\OA\ProjectController;
use App\Model\OACompany;
use App\Model\OAFinance;
use App\Model\OAProjectLx;
use App\Model\OAProjectYs;
use App\Model\OAProjectYsDetail;
use App\Model\OAShenPiLog;
use App\Model\OAStaff;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class ProjectJsLogic extends Controller
{
    //获取结算下拉
    public function getProjectJsSelect($params)
    {
        $roleid = $params['roleid'];

        $uid = $params['uid'];

        $deptid = $params['deptid'];

        $query = OAProjectLx::query();
        $query->where([
            'a.create_role'=>$roleid,
            'a.uid'=>$uid,
            'a.deptid'=>$deptid,
            'a.status'=>2,
            'b.type'=>1,
            'b.status'=>2,
        ]);

        $list = $query->from('project_lx AS a')
                      ->leftJoin('project_ys AS b','b.xmid','=','a.id')
                      ->orderBy('b.updated_at','DESC')
                      ->select(['a.id','a.name','b.id AS ysid'])
                      ->get()
                      ->toArray();

        //过滤已申请的结算
        foreach ($list as $key => $item){
            $isSetJs = OAProjectYs::query()->where('xmid',$item['id'])->where('type',2)->exists();
            if($isSetJs) unset($list[$key]);
        }

        return $list;

    }

    //获取结算数据
    public function getProjectJsData(OAProjectYs $projectJs)
    {

        $project = new ProjectYsLogic();
        $ysInfo = $project->getProjectYsDetail($projectJs,true);

        $baseInfo = $ysInfo->baseInfo;
        unset($ysInfo->baseInfo);
        $ysInfo = $ysInfo->toArray();
        $baseInfo = $baseInfo->toArray();
        $jsInfo = [];
        $costList = $ysInfo['ysData'];
        unset($ysInfo['ysData']);
       $yfList = $this->getPayedMoney($costList);
       //dd($yfList,$costList);
        foreach ($costList as &$js){
            //查已付金额
            $paytype = Arr::get($js,"paytype");
            $ysid = Arr::get($js,"id");
            $js['yf'] = Arr::get($yfList,$ysid,'0.00');
            $js['ysmoney'] = $js['money'];
            $js['jsmoney'] = $js['jsmoney'] > 0 ? $js['jsmoney'] :  $js['money'];
            $js['edit'] = in_array($js['paytype'],[Constant::PAY_TYPE_BX,Constant::PAY_TYPE_FK,0]);
        }
        $history = $ysInfo['history'];
        foreach ($history as &$item){
            $item['username'] = '';
            $item['color'] = '#FFFFFF';
            $item['note_list'] = $item['file_list'] = [];
        }
        $jsInfo['history'] = $history;
        $jsInfo['tax'] = $ysInfo['tax'] = fomateMoney('',$ysInfo['tax']);
        $jsInfo['total'] = $ysInfo['total'] = fomateMoney('',$ysInfo['total']);
        $jsInfo['profit'] = $ysInfo['profit'] = fomateMoney('',$ysInfo['profit']);
        $jsInfo['percent'] = $ysInfo['percent'] = fomateMoney('',$ysInfo['percent']);
        $jsInfo['sub_total'] = $ysInfo['sub_total'] = fomateMoney('',$ysInfo['sub_total']);
        $ysInfo['start'] = $jsInfo['start'] = $baseInfo['start'];
        $ysInfo['stop'] = $jsInfo['stop'] = $baseInfo['stop'];
        $jsInfo['cost'] = $ysInfo['cost'];
        $jsInfo['offer'] = $ysInfo['offer'];

        $baseInfo['rate'] = OACompany::query()->where('id',$baseInfo['gsid'])->value('tax');
        $baseInfo['rate'] = $baseInfo['rate'] / 100;
        $ysInfo['seller'] = $jsInfo['seller'] = OAStaff::query()->where('id',$ysInfo['seller_id'])->value('username');
        $jsInfo['file_list'] = $jsInfo['design_list'] = $jsInfo['activity_list'] = [];
        return ['baseInfo'=>$baseInfo,'ys'=>$ysInfo,'js'=>$jsInfo,'costList'=>$costList];

    }

    //获取结算时已付金额
    protected function getPayedMoney(array $costList)
    {

        $fkList = OAFinance::query()
            ->whereIn("ysid",array_column($costList,'id'))
            ->selectRaw('sum(money) AS yf, ysid')
            ->groupBy('ysid')
            ->get()
            ->toArray();
        return array_column($fkList,'yf','ysid');
    }

    //保存提交预算数据
    public function saveProjectData($params,OAProjectYs $projectYs=null)
    {
        try{
            DB::beginTransaction();
            $isSave = $params['is_save'];
            $roleid = $params['roleid'];
            $uid = $params['uid'];
            $xmid = Arr::get($params,'xmid',0);
            $projectLx = OAProjectLx::find($xmid);
            if(!$projectLx) throw new BusinessException("立项不存在");
            $ysid = $params['ysid'] ?? 0;
            $js = $params['js'];
            $costList = $params['costList'];
            $newJs = Arr::get($params,'newJs',[]);
            if(empty($js['file_list'])) throw new \Exception('结算附件未添加,请检查');
            if(empty($js['design_list'])) throw new \Exception('设计附件未添加,请检查');
            if(empty($js['activity_list'])) throw new \Exception('活动附件未添加,请检查');
            if(is_null($projectYs)){
                $ysInfo = OAProjectYs::find($ysid);
            }else{
                $ysInfo = $projectYs;
            }
            $node_id = $this->getCurrentNode($ysInfo->work_id,$roleid);
            //提交
            if(!$isSave && isPM()){
                $nextRole = $this->getNextApprover($node_id, $ysInfo->work_id, 1);
                $roleid = $nextRole['roleid'];
                $node_id = $nextRole['node_id'];
                $ysInfo->status = Arr::get($nextRole, 'status');
            }
            $editData = [
                'tax' => resetMoney($js['tax']),
                'total' => resetMoney($js['total']),
                'profit' => resetMoney($js['profit']),
                'percent' => $js['percent'],
                'roleid' => $roleid,
                'desc' => $js['desc'] ?? '',
                'is_save' => $isSave,
                'node_id' => $node_id,
                'offer' => resetMoney($js['offer']),
                'cost' => resetMoney($js['cost']),
                'updated_at' => date('Y-m-d H:i:s'),
                "sub_total"=>resetMoney(Arr::get($js,'sub_total','0.00')),
                'start' => $js['start'] ?? '',
                'stop' => $js['stop'] ?? '',
            ];
                if($projectYs){
                    // 查记录并且保存
                    $jsid = $projectYs->id;
                    $log = $this->checkDifferentData([
                        'id'=>$jsid,
                        'js'=>$params['js'],
                        'costList'=>$costList,
                        'roleid'=>$roleid,
                        'newJs'=>$newJs,
                        "is_save"=>true,
                    ],'js');
                    //添加修改记录
                $projectYs->fill($editData)->save();
                }else{
                    //结算初始化
                    $jsData = [
                        'xmid' => $xmid,
                        'uid' => $uid,
                        'type' => OAProjectYs::PROJECT_JS,
                        'role_list' => $ysInfo->role_list,
                        'seller_id' => $ysInfo->seller_id,
                        'approver' => $ysInfo->approver,
                        'create_role' => $params['roleid'],
                        'created_at' => date('Y-m-d H:i:s'),
                        'work_id' => $ysInfo->work_id,
                        'status' => Constant::STATUS_OFF,
                        'ysid' => $ysid,
                        "deptid" =>$projectLx->deptid,
                    ];
                    $projectYs = OAProjectYs::create(array_merge($editData,$jsData));
                    $jsid = $projectYs->id;
                    $log = [];
                    $costList = Arr::get($params,'costList',[]);
                    $newJs = Arr::get($params, 'newJs', []);
                    $costList = array_merge($costList, $newJs);
                    $this->handleYsDetailData($costList, $projectYs, true, true);
                }

            $logData = [
                'work_id'=>$ysInfo->work_id,
                'uid'=>$uid,
                'roleid'=>$params['roleid'],
                'id'=>$jsid,
                'state'=>2,
            ];
            if($log) {
                $logData['note'] = is_array($log) ? implode(';',$log) : $log;
                $this->saveShenPiLog($logData);
            }else{
                if(!$isSave && isPM()){
                    $logData['note'] = "提交结算";
                    $logData['state'] = OAShenPiLog::SHENPI_STATUS_PASS;
                    $this->saveShenPiLog($logData);
                }
            }
            //附件
            $this->saveFileList($jsid,$js['file_list'],FILE_JS,$ysInfo->work_id);
            $this->saveFileList($jsid,$js['design_list'],FILE_JS_DESIGN,$ysInfo->work_id);
            $this->saveFileList($jsid,$js['activity_list'],FILE_JS_ACTIVITY,$ysInfo->work_id);

            DB::commit();

            return $jsid;

        }catch (\Exception $e){
            DB::rollBack();
           // dump($e);
            throw new BusinessException($e->getMessage());
        }
    }

    //获取结算详情
    public function getJsDetail($params,OAProjectYs $projectJs)
    {
       $projectYs = OAProjectYs::query()->find($projectJs->ysid);
       $ysDetail = $this->getProjectJsData($projectYs);
       //文件列表
        $ysDetail['js']['file_list'] = $this->getFileList($projectJs->id,FILE_JS);
        $ysDetail['js']['design_list'] = $this->getFileList($projectJs->id,FILE_JS_DESIGN);
        $ysDetail['js']['activity_list'] = $this->getFileList($projectJs->id,FILE_JS_ACTIVITY);
       //预算结算详情
        $newJs = [];
        $ysDetail['js']['tax'] = fomateMoney('',$projectJs->tax);
        $ysDetail['js']['total'] = fomateMoney('',$projectJs->total);
        $ysDetail['js']['profit'] = fomateMoney('',$projectJs->profit);
        $ysDetail['js']['percent'] = $projectJs->percent;
        $ysDetail['js']['offer'] = fomateMoney('',$projectJs->offer);
        $ysDetail['js']['cost'] = fomateMoney('',$projectJs->cost);
        $ysDetail['js']['sub_total'] = fomateMoney('',$projectJs->sub_total);
        $ysDetail['js']['desc'] = $projectJs->desc;
        $ysDetail['js']['start'] = $projectJs->start;
        $ysDetail['js']['stop'] = $projectJs->stop;

        $log = new ApproveHistory();
        $ysDetail['js']['history'] = $log->getApproveHistory($projectJs);
        $extend = $this->getInfoExtend($projectJs,$params['roleid']);
        $ysDetail['id'] = $params['id'];
        $ysDetail['work_id'] = $projectJs->work_id;

        foreach ($ysDetail['costList'] as $key => $item){
            if($item['is_js']) {
                $newJs[] = $item;
                Arr::forget($ysDetail['costList'], $key);
            }
        }
        $ysDetail['newJs'] = $newJs;

        return array_merge($extend,$ysDetail);

    }


}
